<?php
apf_require_class('Aifang_Core_Debugger');
class APF_Http_Client_Curl {

    private $curl;

    private $url;

    /**
     * @return APF_Http_Client_Curl
     */
    public function __construct() {
        $this->curl = curl_init();
        $this->init();
    }

    public function init() {
        $this->set_attribute(CURLOPT_HTTPHEADER, array(
                "Content-type:text/xml; charset=utf-8"
        ));
        $this->set_attribute(CURLOPT_RETURNTRANSFER, 1);
        $this->set_attribute(CURLOPT_CONNECTTIMEOUT, 1);
        $this->set_attribute(CURLOPT_TIMEOUT, 1);
    }

    /**
     * 请求curl
     * @var string
     */
    private $_url = null;

    public function set_url($url) {
        $this->_url = $url;
        $this->url = $url;
        curl_setopt($this->curl, CURLOPT_URL, $url);
    }

    public function set_attribute($name, $value) {
        curl_setopt($this->curl, $name, $value);
    }

    public function set_timeout($time) {
        $this->set_attribute(CURLOPT_TIMEOUT, $time);
    }

    /**
     * @return boolean
     */
    public function execute() {

        $debugger = Aifang_Core_Debugger::get_instance();
        $bench_key = "client_curl url=>" . $this->url;
        $debugger->apf_benchmark_begin($bench_key);
        $this->response_text = curl_exec($this->curl);
        $debugger->apf_benchmark_end($bench_key);

        $this->set_i();
        // 以下是正常流程


        $this->curl_info = curl_getinfo($this->curl);

        $debugger->debug("APF_Http_Client_Curl curl rs=>{$this->curl_info['http_code']} " . $bench_key);
        if($this->curl_info['http_code'] == 200) {
            return true;
        } else {
            if(Apf::get_instance()->get_config('log_curl_timeout_error')) {
                trigger_error("curl not 200 curl_url is => :{$this->_url}:  http_code => {$this->curl_info['http_code']} error_info => :" . curl_error($this->curl) . ":");
            }
            return false;
        }
    }

    private $response_text;

    private $curl_info;

    public function get_response_text() {
        return $this->response_text;
    }

    public function get_curl_info() {
        return $this->curl_info;
    }

    public function __destruct() {
        curl_close($this->curl);
    }

    /**
     * curl调用计数器
     * @var int
     */
    private $_i = 0;

    /**
     * 更新curl计数器
     */
    public function set_i() {
        $this->_i++;
    }
}
?>
